package com.example.demo.api;

import com.example.demo.model.User;
import com.example.demo.model.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserAPI {

    @Autowired
    private UserMapper userMapper;
//一个登录接口,一个注册接口
    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest request){
//        1.取数据库中查看
        User user=userMapper.selectByName(username);
        if(user==null||!user.getPassword().equals(password)){
            System.out.println("登陆失败,用户名或者密码错误!"+user);
            return new User();
        }
//        登陆成功,创建会话
        HttpSession session=request.getSession(true);
//        创建session
        session.setAttribute("user",user);
//        在返回之前,设置密码为空
        user.setPassword("");
        return user;
    }
//注册
@PostMapping("/register")
@ResponseBody
public Object register(String username, String password) {
    User user = null;
    try {
        user = new User();
        user.setUsername(username);
        user.setPassword(password);
        System.out.println("register! user=" + user);
        int ret = userMapper.insert(user);
        System.out.println("ret: " + ret);
        user.setPassword("");
    } catch (org.springframework.dao.DuplicateKeyException e) {
        System.out.println("注册失败");
        user = new User();
    }
    return user;
}
//实现页面获取到的是当前的哪一个用户的信息

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getuserInfo(HttpServletRequest request){
//        获取session
        HttpSession session=request.getSession(false);
//        对session进行判断
        if(session==null){
            System.out.println("获取不到session对象");
            return new User();
        }
//        获取user
        User user=(User) session.getAttribute("user");
       //对得到的用户信息进行判断
        if(user==null){
            System.out.println("获取不到user对象");
            return new User();
        }
        user.setPassword("");
        return user;
    }


}
